package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.easemob.easeui.domain.EaseUser;
import com.xgkj.diyiketang.data.CaiPinInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.hxsdk.DemoHelper;
import com.xgkj.diyiketang.hxsdk.PreferenceManager;
import com.xgkj.diyiketang.task.DishAddTask;
import com.xgkj.diyiketang.task.DishEditTask;
import com.xgkj.diyiketang.task.UpdateIconTask;
import com.xgkj.diyiketang.task.UploadImage;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.JpushUtil;
import com.xgkj.diyiketang.util.OnMultClickListener;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.MoneyInputEditText;
import com.xgkj.diyiketang.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CreateDishActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private RelativeLayout titleLayout;
    private TextView back;
    private TextView titleName;
    private TextView saveinfo;
    private LinearLayout footLayout;
    private RelativeLayout headImgLayout;
    private TextView uploadImgText;
    private ImageView updateImg;
    private RelativeLayout dishnameLayout;
    private TextView dishLeft;
    private ClearableEditText dishname;
    private RelativeLayout priceLayout;
    private TextView priceLeft;
    private MoneyInputEditText dishPrice;
    private RelativeLayout dishdescLayout;
    private TextView descLeft;
    private ClearableEditText dishDesc;
    private PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 0;
    private static final int CHOOSE_REQUEST = 11;
    private static final int CROP_REQUEST = 2;
    private File mFile;
    private String local_url;
    private static final String CAMERA_FILE = "diyiketang/img";
    private int taskId = -1;
    private int updateTaskId = -1;
    private int createTaskId = -1;
    private String dish_name;
    private String dish_price;
    private String dish_desc;
    private String dishImageId;
    private ImageView dishImage;
    Bitmap bitmap;
    private int from;
    private String dishId;
    private CaiPinInfo dishInfo;
    private InputMethodManager im;
    private String dish_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_dish);
        mContext = this;
        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "IMG"+ System.currentTimeMillis()+".jpeg";
        mFile = new File(folder,fileName);
        initView();
        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null){
            from = intent.getIntExtra("FROM",0);
            dishInfo = (CaiPinInfo) intent.getSerializableExtra("DISHINFO");
        }

        if (from ==0){
            finish();
            return;
        }
        titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(this);
        titleName = (TextView) findViewById(R.id.title_name);
        saveinfo = (TextView) findViewById(R.id.saveinfo);
        saveinfo.setOnClickListener(new OnMultClickListener(){
            @Override
            public void onMultClick(View v) {
                super.onMultClick(v);
                if (checkInput()) {
                    doUpdateDish();
                }
            }
        });
        footLayout = (LinearLayout) findViewById(R.id.foot_layout);
        findViewById(R.id.submit_btns).setOnClickListener(this);
        headImgLayout = (RelativeLayout) findViewById(R.id.head_img_layout);
        headImgLayout.setOnClickListener(this);
        uploadImgText = (TextView) findViewById(R.id.upload_img_text);
        updateImg = (ImageView) findViewById(R.id.update_img);
        dishImage = (ImageView) findViewById(R.id.dish_image);
        dishname = (ClearableEditText) findViewById(R.id.dishname);
        dishPrice = (MoneyInputEditText) findViewById(R.id.dish_price);
        dishPrice.setNumberStyle(true);
        dishPrice.setMoneyMaxInput(100000);
        dishDesc = (ClearableEditText) findViewById(R.id.dish_desc);
        initPopWindow();

        if (from == 1){
            dishImage.setVisibility(View.GONE);
            saveinfo.setVisibility(View.GONE);
            uploadImgText.setVisibility(View.VISIBLE);
            updateImg.setVisibility(View.VISIBLE);
            footLayout.setVisibility(View.VISIBLE);
        }else if (from ==2) {
            dishImage.setVisibility(View.VISIBLE);
            saveinfo.setVisibility(View.VISIBLE);
            uploadImgText.setVisibility(View.GONE);
            updateImg.setVisibility(View.GONE);
            footLayout.setVisibility(View.GONE);
            dishId = dishInfo.getDishId();
            dish_url = dishInfo.getDishBigLogo();
            ImageCache.getInstance(mContext).loadBitmapToView(dishImage,dish_url,null);
            dish_name = dishInfo.getDishName();
            if (dish_name != null){
                dishname.setText(dish_name);
                dishname.setSelection(dish_name.length());
            }

            dish_price = dishInfo.getPrice();
            if (dish_price != null){
                dishPrice.setText(dish_price);
            }

            dish_desc = dishInfo.getDDescription();

            if (dish_desc != null){
                dishDesc.setText(dish_desc);
            }
        }
    }

    private void initPopWindow(){
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    private void uploadImage(String path){
        if(taskId != -1){return;}

        UploadImage task = new UploadImage(path);
        task.addListener(uploadImageListener);
        taskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void doCreateDish(){
        DishAddTask addTask = new DishAddTask(dishImageId,dish_price,dish_name,dish_desc);
        addTask.addListener(uploadImageListener);
        createTaskId = getEatShowApp().getTaskManager().addTask(addTask);
    }

    private void doUpdateDish(){
        DishEditTask editTask = new DishEditTask(dishId,dishImageId,dish_price,dish_name,dish_desc);
        editTask.addListener(uploadImageListener);
        updateTaskId = getEatShowApp().getTaskManager().addTask(editTask);
    }

    private boolean checkInput(){
        dish_name = dishname.getText().toString();
        dish_price = dishPrice.getText().toString();
        dish_desc = dishDesc.getText().toString();
        if (ViewUtil.isNull(dishImageId) && ViewUtil.isNull(dish_url)){
            Toast.makeText(mContext,R.string.dishiamge_not_null,Toast.LENGTH_SHORT).show();
            return false;
        }
        if (ViewUtil.isNull(dish_name) || ViewUtil.isNull(dish_price)){
            Toast.makeText(mContext,R.string.message_not_null,Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private TaskEventListener uploadImageListener = new ShowToastTaskEventListener(this){
        @Override
        public void handleTaskCompleted(int taskid, int result, Object data) {
            super.handleTaskCompleted(taskid, result, data);
            if(taskid == taskId){

                taskId = -1;
                if(data != null){
                    JSONObject json = (JSONObject) data;
                    dishImageId = json.getString("imageId");
                    PalLog.e("图片id",dishImageId);
                }
                if(mFile.exists()){
                    mFile.delete();
                }
            }else if(taskid == updateTaskId){
                updateTaskId = -1;
                finish();
            }else if (taskid == createTaskId){
                createTaskId = -1;
                finish();
            }

        }

        @Override
        public void handleTaskError(int taskid, int errorCode, String errorMsg) {
            super.handleTaskError(taskid, errorCode, errorMsg);
            if(taskid == taskId){
                taskId = -1;
            }else if(taskid ==updateTaskId){
                updateTaskId = -1;
            }else if (taskid == createTaskId){
                createTaskId = -1;
            }
        }

        @Override
        public void handleTaskMessage(int taskid, Object data) {
            super.handleTaskMessage(taskid, data);
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.submit_btns:
                if (checkInput()){
                    doCreateDish();
                }
                break;

            case R.id.takephoto:
                popWindow.dismiss();
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera_intent
                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
                break;
            case R.id.cancle:
                popWindow.dismiss();
                break;
            case R.id.back:
               finish();
                break;

            case R.id.head_img_layout:
                im.hideSoftInputFromWindow(CreateDishActivity.this.getCurrentFocus().getWindowToken(),0);
                popWindow.showAtLocation(view, Gravity.BOTTOM,0,0);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (!mFile.exists()) {
                    return;
                }
                Uri uri = Uri.fromFile(mFile);
                startPhotoZoom(uri);
//                uploadImage(mFile.getAbsolutePath());
                break;

            case CHOOSE_REQUEST:
                if (resultCode != RESULT_OK){
                    return;
                }
                if (data == null)
                    return;
                Uri choose_uri = data.getData();
                startPhotoZoom(choose_uri);
                break;

            case CROP_REQUEST:
                if (resultCode != RESULT_OK){
                    return;
                }
                if (data == null)
                    return;
                if (!mFile.exists()) {
                    return;
                }
                try {
                    bitmap = ViewUtil.revitionImageSize(mFile.getAbsolutePath());
                    if (bitmap != null) {
                        dishImage.setVisibility(View.VISIBLE);
                        uploadImgText.setVisibility(View.GONE);
                        updateImg.setVisibility(View.GONE);
                        dishImage.setImageBitmap(bitmap);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }


                uploadImage(mFile.getAbsolutePath());
//                bitmap = (Bitmap) data.getExtras().get("data");
//                if (bitmap != null) {
//                    dishImage.setVisibility(View.VISIBLE);
//                    uploadImgText.setVisibility(View.GONE);
//                    updateImg.setVisibility(View.GONE);
//                    dishImage.setImageBitmap(bitmap);
//                    BufferedOutputStream out = null;
//                    try {
//                        out = new BufferedOutputStream(new FileOutputStream(mFile));
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                    boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG,
//                            80, out);
//                    uploadImage(mFile.getAbsolutePath());
//                }
                break;

            case 300:
                PalLog.e("返回resultcode",resultCode+"");
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap != null && !bitmap.isRecycled()){
            bitmap.recycle();
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            local_url = GetImagePathUtil.getPath(mContext, uri);
            uri = Uri.fromFile(new File(local_url));
        }
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 2);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 750);
        intent.putExtra("outputY", 500);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(mFile));
        startActivityForResult(intent, CROP_REQUEST);
    }
}
